<template>
  <BasicModal
    title="添加设备配置"
    v-bind="$attrs"
    width="700px"
    @register="register"
    :destroyOnClose="true"
    @ok="test"
    :closeFunc="close"
    :body-style="{ marginLeft: '10px', marginRight: '10px' }"
  >
    <template v-if="key === 'add'">
      <div class="mb-24px">
        <Steps :current="current">
          <Step title="设备配置详情" />
          <Step title="传输配置" />
          <Step title="警告规则" />
          <Step title="设备预配置" />
        </Steps>
      </div>
      <div>
        <DeviceFileDetailForm
          v-show="current == 0"
          ref="deviceFileDetailForm"
          @upload="getImgData"
          @delete-img="deleteImgData"
        />
        <div v-show="current == 1">
          <TransportConfiguration ref="transportConfiguration" />
        </div>
        <div v-show="current == 2">
          <Alarm ref="alarm" />
        </div>
        <DeviceFilePreConfiguredForm v-show="current == 3" ref="deviceFilePreConfiguredForm" />
      </div>
      <div class="absolute w-full mb-12px bottom-0">
        <Button v-show="current != 0" @click="previous">上一步</Button>
        <Button type="primary" v-show="current != 3" @click="next" class="mr-28px float-right"
          >下一步</Button
        >
      </div>
    </template>
    <template v-else>
      <Upload
        accept=".json"
        :max-count="1"
        :beforeUpload="uploadJson"
        listType="text"
        @remove="removeJson"
      >
        <Button type="primary">上传JSON文件</Button>
      </Upload>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  /**
   * key 判断是导入还是添加
   * **/
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Upload } from 'ant-design-vue';
  import { Steps, Step, Button } from 'ant-design-vue';
  import Alarm from './Alarm/Alarm.vue';
  import TransportConfiguration from './TransportConfiguration.vue';
  import DeviceFileDetailForm from './DeviceFileDetailForm.vue';
  import DeviceFilePreConfiguredForm from './DeviceFilePreConfiguredForm.vue';
  import { postDeviceProfile } from '/@/api/thingsborad/profile/deviceProfile/deviceProfile';
  const emit = defineEmits(['add']);
  let key = ref<string>();
  let current = ref(0);
  // deviceFileDetailForm设备配置详情表单实例
  const deviceFileDetailForm = ref<any>(null);
  // deviceFilePreConfiguredForm 设备预配置表单实例
  const deviceFilePreConfiguredForm = ref<any>(null);
  //transportConfiguration 传输配置表单实例
  const transportConfiguration = ref<any>(null);

  //alarm 告警实例
  const alarm = ref<any>(null);
  //导入文件的内容
  const fileContent = ref<any>(null);
  //设配配置数据
  let data = ref<Recordable>({
    name: '',
  });
  let imgData = ref<any>(null);
  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    key.value = data?.key;
    setModalProps({
      title: data?.key == 'add' ? '添加设备配置' : '导入设备配置',
    });
  });
  function uploadJson(file: any) {
    const reader: any = new FileReader();
    reader.readAsText(file);
    reader.addEventListener('load', () => {
      try {
        const jsonData = JSON.parse(reader.result);
        fileContent.value = jsonData;
      } catch (error) {
        console.error('JSON文件读取或解析错误:', error);
      }
    });
    return false;
  }

  function removeJson() {
    fileContent.value = {};
    return true;
  }

  //下一步
  async function next() {
    if (current.value === 0) {
      deviceFileDetailForm.value.validate().then(() => {
        current.value++;
      });
    } else {
      current.value++;
    }
  }
  //上一步
  async function previous() {
    if (current.value === 3) {
      deviceFilePreConfiguredForm.value.validate().then(() => {
        current.value--;
      });
    } else {
      current.value--;
    }
  }
  function getImgData(data: any) {
    imgData.value = data;
  }
  function deleteImgData() {
    imgData.value = null;
  }
  async function close() {
    current.value = 0;
    imgData.value = null;
    fileContent.value = null;
    return true;
  }
  //弹窗确认
  async function test() {
    if (key.value === 'add') {
      //设配详情

      await deviceFileDetailForm.value.validate().then((res) => {
        if (res.defaultDashboardId != undefined) {
          res.defaultDashboardId = JSON.parse(res.defaultDashboardId);
        }
        if (res.defaultEdgeRuleChainId != undefined) {
          res.defaultEdgeRuleChainId = JSON.parse(res.defaultEdgeRuleChainId);
        }
        if (res.defaultRuleChainId != undefined) {
          res.defaultRuleChainId = JSON.parse(res.defaultRuleChainId);
        }
        res.image = imgData.value;

        data.value = res;
        data.value.profileData = { configuration: {} };
      });
      //设备预配置
      await deviceFilePreConfiguredForm.value.validate().then((res) => {
        data.value.provisionType = res.type;
        if (res.certificateRegExPattern) {
          res.provisionDeviceSecret = res.PEMprovisionDeviceSecret;
          res.certificateValue = res.PEMprovisionDeviceSecret;
        }
        if (res.provisionDeviceKey) {
          data.value.provisionDeviceKey = res.provisionDeviceKey;
          delete res.provisionDeviceKey;
        }
        data.value.profileData.provisionConfiguration = res;
      });
      //传输配置
      await transportConfiguration.value.getTransportConfiguration().then((res) => {
        data.value.transportType = res.type;
        data.value.profileData.transportConfiguration = res;
      });
      //告警
      let alarmData = alarm.value.getAlarmsData();

      if (alarmData.length > 0) {
        data.value.profileData.alarms = alarmData;
      }
      data.value.type = 'DEFAULT';
      data.value.profileData.configuration.type = 'DEFAULT';

      try {
        await postDeviceProfile(data.value);
      } catch (error) {
        console.error('添加设备配置失败', error);
      }
      deviceFileDetailForm.value.resetFields();
      deviceFilePreConfiguredForm.value.resetFields();
    } else {
      try {
        await postDeviceProfile(fileContent.value);
      } catch (error) {
        console.error('添加设备配置失败', error);
      }
    }
    emit('add');
    current.value = 0;
    imgData.value = null;
    fileContent.value = null;
    closeModal();
  }
</script>
